package Test_1208;

/**
 * Created with Intellij IDEA
 * Description:
 * User: 星辰
 */
public class BinarySearchTree {
    static  class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root;
    //插入数据
    public void insert(int key){
        if(root==null){
            root=new TreeNode(key);
            //root.val=key;
            return ;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        TreeNode node=new TreeNode(key);
        while(cur!=null){
            parent=cur;
            if(key< cur.val){
                cur=cur.left;
            }else if(key< cur.val){
                cur=cur.right;
            }else{
                return;
            }
        }
        if(parent.val>key){
            parent.left=node;
        }else {
            parent.right=node;
        }
    }
    //搜索数据
    //小于向左，大于向右，等于找到
    public TreeNode search(int val){
        TreeNode cur=root;
        while(cur!=null){
            if(val< cur.val){
                cur=cur.left;
            }else if(val< cur.val){
                cur=cur.right;
            }else{
                return cur;
            }
        }
        return null;
    }
    public TreeNode search1(int val){
        if(root==null){
            return null;
        }
        if(val< root.val){
            search1(root.left.val);
        }else if(val< root.val){
            search1(root.right.val);
        }else{
            return root;
        }
        return null;
    }
}
